#include "MyOpenButton.h"
#include <QPainter>
#include <QThread>
#include <iostream>
#include <QMouseEvent>
MyOpenButton::MyOpenButton(int width, int height, QWidget *parent):
    QPushButton(parent)
    ,m_checked(false)
    ,m_width(width)
    ,m_height(height)
{
    setFixedSize(m_width, m_height);
    int thumbwh = m_height*0.8;
    m_thumbRect = QRectF(3, 3, thumbwh, thumbwh);
    m_thumbRectOpen = QRectF(m_width - thumbwh - 5, 3, thumbwh, thumbwh);
}

MyOpenButton::~MyOpenButton()
{

}

bool MyOpenButton::isChecked() const {
    return m_checked;
}

void MyOpenButton::setChecked(bool checked) {
    if (m_checked != checked) {
        m_checked = checked;
        update();
        emit toggled(m_checked);
    }
}

void MyOpenButton::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // Draw the background
    painter.setBrush(m_checked ? Qt::green : Qt::red);
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(), 15, 15);

    // Draw the thumb
    painter.setBrush(Qt::white);
    if(m_checked)
    {
        painter.drawEllipse(m_thumbRectOpen);
    }
    else
    {
        painter.drawEllipse(m_thumbRect);
    }
}

void MyOpenButton::mousePressEvent(QMouseEvent * event)
{
    if (m_thumbRect.contains(event->pos())) {
        m_checked = true;
    }
    else if(m_thumbRectOpen.contains(event->pos()))
    {
        m_checked = false;
    }

    emit toggled(m_checked);
    QPushButton::mousePressEvent(event);
}

